



import 'dart:async';

import 'package:bike_ride/api/common_repository.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/error.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/round_tab_indicator.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/wallet/model/transaction_item_m.dart';
import 'package:bike_ride/res/global/globals.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

final _tabs = {
  0: S.current.all,
  1: S.current.inCome,
  -1: S.current.expend,
};

/// 交易明细页
class TransactionsPage extends StatefulWidget {
  const TransactionsPage({super.key});

  @override
  State<TransactionsPage> createState() => _TransactionsPageState();
}

class _TransactionsPageState extends State<TransactionsPage> with SingleTickerProviderStateMixin{
  final StreamController<List<TransactionItemM>> _streamController = StreamController();
  final ScrollController _scrollController = ScrollController();
  List<TransactionItemM> _list = [];

  late TabController _tabController;
  final _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();

  int inOrOut = 0;
  int _page = 1;
  final int _size = 10;
  bool _haveMore = true;

  Future _future({int bPage = 1})async{
    if(bPage == 1){
      EasyLoading.show();
    }
    final data = await CommonRepository.getTransactionsIdl(inOrOut: inOrOut, page: bPage, listRows: _size);
    EasyLoading.dismiss();
    if (data.isNotEmpty && data[0].errorMsg != null) {
      _streamController.safetyError(data[0].errorMsg.toString());
    } else {
      if (bPage == 1) {
        _list = data;
      } else {
        _list.addAll(data);
      }
      _page = bPage + 1;
      _haveMore = data.length <= _size;
      _streamController.safetyAdd(_list);
    }
  }


  @override
  void initState() {
    super.initState();
    _tabController = TabController(vsync: this, length: _tabs.length, initialIndex: 0)..addListener(() {
      if (_tabController.indexIsChanging) {
        _streamController.add([]);
        inOrOut = _tabs.keys.toList()[_tabController.index];
        _refreshIndicatorKey.currentState?.show();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _refreshIndicatorKey.currentState?.show();
    });

    _scrollController.addListener(() {
      if (_scrollController.position.maxScrollExtent ==
          _scrollController.position.pixels) {
        if (_haveMore) {
          _future(bPage: _page);
        }
      }
    });
  }

  @override
  void dispose() {
    _streamController.close();
    _scrollController.dispose();
    _tabController.dispose();
    _refreshIndicatorKey.currentState?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        children: [
          PageTitleWidget(title: S.current.tradeDetail),
          Container(
            decoration: BoxDecoration(
              color: ColorStyles.color_FFFFFF,
              boxShadow: [
                BoxShadow(
                  color: ColorStyles.color_000000.withOpacity(0.2),
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: TabBar(
              controller: _tabController,
              dividerHeight: 0,
              indicatorSize: TabBarIndicatorSize.tab,
              indicator: RoundUnderlineTabIndicator(
                  borderSide: BorderSide(
                    width: 2.rpx,
                    color: Theme.of(context).colorScheme.primary,
                  )
              ),
              labelStyle: TextStyle(color: Colors.black87,fontSize: 32.rpx,fontWeight: FontWeight.w600),
              unselectedLabelStyle: TextStyle(color: Colors.black87,fontSize: 30.rpx,fontWeight: FontWeight.w400),
              tabs: [for (final tab in _tabs.values) Padding(padding: const EdgeInsets.only(bottom: 5),child: VgTab(text: tab,),)],
            ),
          ),
          Expanded(child: RefreshIndicator(
            key: _refreshIndicatorKey,
            onRefresh: _future,
            child: StreamBuilder<List<TransactionItemM>>(
                stream: _streamController.stream,
                initialData: const [],
                builder: (context,snapshot){
                  final hasData = snapshot.data != null &&
                      (snapshot.data!.isNotEmpty || _list.isNotEmpty);
                  return ListView.builder(
                    controller: _scrollController,
                    padding: EdgeInsets.symmetric(vertical: 20.rpx),
                    itemCount: hasData ? _list.length : 1,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      if (hasData) {
                        return Column(
                          children: [
                            _ItemWidget(
                                onRefresh: () => _future(),
                                model: _list[index]),
                            if (index == _list.length - 1)
                              ...[
                                const SizedBox(height: 4,),
                                Center(
                                    child: Text(
                                      S.current.noMore,
                                      style: TextStyle(
                                          color: Colors.grey.withOpacity(0.6)),
                                    ))
                              ]
                          ],
                        );
                      }
                      return Center(
                        child: ErrorInfoWidget(
                          retry: ()=>_future(),
                          errorMsg: snapshot.error,
                        ),
                      );
                    },
                  );
                }),
          ))
        ],
      ),
    );
  }
}


class _ItemWidget extends StatelessWidget {
  final TransactionItemM model;
  final Function() onRefresh;
  const _ItemWidget({required this.model, required this.onRefresh});

  @override
  Widget build(BuildContext context) {
    final firstTextStyle = TextStyle(fontSize: 28.rpx,color: ColorStyles.color_666666);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24.rpx,vertical: 16.rpx),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: ColorStyles.color_F5F5F5)
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(model.content??'-',style: TextStyle(fontSize: 28.rpx,fontWeight: FontWeight.bold),),
              Builder(builder: (context){
                num money = model.amount ?? 0;
                final isIn = model.inOrOut == 1;
                final isGift = model.amount == 0 && (model.giftAmount??0) >0;
                final isGiftAntAmount = (model.giftAmount??0) >0 && (model.amount??0) >0;
                if((model.totalAmount??0) >0){
                  money = model.totalAmount!;
                }else{
                  if(isGiftAntAmount){
                    money = model.giftAmount! + model.amount!;
                  }else if(isGift){
                    money = model.giftAmount!;
                  }
                }
                return Text('${isIn?'+':'-'}$money${S.current.yuan}',style: TextStyle(fontSize: 24.rpx,color: isIn?const Color(0xFF68CA00):ColorStyles.color_FF4D4F),);
              })
            ],
          ),
          SizedBox(height: 8.rpx,),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(padding: EdgeInsets.only(top: 8.rpx),child: Icon(Icons.access_time,size: 26.rpx,color: ColorStyles.color_333333,),),
              Text(formatTimestamp(model.createTime),style: firstTextStyle,),
              const Spacer(),
              Builder(builder: (context){
                String txt = '-';
                final isGiftAntAmount = (model.giftAmount??0) >0 && (model.amount??0) >0;
                final isGift = model.amount == 0 && (model.giftAmount??0) >0;

                if(model.inOrOut == 1){
                  txt = Globals.incomeTypeMap[model.type]??'-';
                }else if(model.inOrOut == -1){
                  if(model.paymentType! == 5 && isGiftAntAmount){
                    txt = '${S.current.payBalance}-${model.amount}${S.current.yuan},${S.current.giftBonus}-${model.giftAmount}';
                  }else {
                    if(isGift){
                      txt = S.current.giftBonus;
                    }else{
                      txt = '${Globals.payoutTypeMap[model.paymentType]}${S.current.pay}';
                    }
                  }
                }
                return ConstrainedBox(
                  constraints:
                      BoxConstraints(minHeight: 30.rpx, maxWidth: 300.rpx),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    physics: const BouncingScrollPhysics(),
                    child: Text(
                      txt,
                      style: firstTextStyle.copyWith(
                          color: ColorStyles.color_666666),
                    ),
                  ),
                );
              }),
            ],
          ),
        ],
      ),
    );
  }
}
